package com.byl.modules.wx.gzh.service.impl;

import com.byl.modules.wx.gzh.dao.AccessTokenDao;
import com.byl.modules.wx.gzh.service.AccessTokenService;
import com.byl.modules.wx.gzh.utils.ApiConstant;
import com.byl.sdk.gson.GsonUtils;
import com.byl.sdk.utils.HttpUtils;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

/**
 * Created by Administrator on 2019/9/19.
 */
@SuppressWarnings("ALL")
@Service
public class AccessTokenServiceImpl implements AccessTokenService {
    Logger logger= LoggerFactory.getLogger(AccessTokenServiceImpl.class);
    HashMap<String,Map> tokenMap=new HashMap<String,Map>();

    @Autowired
    AccessTokenDao accessTokenDao;

    @Override
    public Map token() {
        String appid="wxc4c5740df406927b";
        if(tokenMap.containsKey(appid)){
            Map map=tokenMap.get(appid);
            long now=System.currentTimeMillis();
            long maxtime=Long.parseLong(map.get("expires_in").toString());
            if(now>=maxtime){
              return  refreshToken(appid);
            }else{
               return map;
            }
        }else{
            return  refreshToken(appid);
        }
    }

    /**
     * 刷新获取token
     * @param appid
     * @return
     */
    private Map refreshToken(String appid){
        String url=ApiConstant.getInstance().getToken(appid,"849a6a2f4b36490ae00d7521c8f7e1be");
        String rs= HttpUtils.get(url);
        logger.info(appid+">>>>获取token结果："+rs);
        JsonObject jo=GsonUtils.toJsonObject(rs);
        if(jo.has("errcode")){
            Map map=new HashMap();
            map.put("errcode",jo.get("errcode"));
            map.put("errmsg",jo.get("errmsg"));
            return map;
        }else{
            String token=jo.get("access_token").getAsString();
            int time=jo.get("expires_in").getAsInt();
            time=time-200;
            long now=System.currentTimeMillis();
            now=now+time*1000;
            Map tmp=new HashMap();
            tmp.put("token",token);
            tmp.put("expires_in",now);
            tokenMap.put(appid,tmp);
            return tmp;
        }
    }
}
